package com.shiwei.is.tools;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocketListener;

/**
 * File: null.java
 * Creator: dingpwen
 * Company: shiwei
 * Created on: 2021/3/26 10:31
 * Email: dingpwen@gmail.com
 * Details: TODO
 */
public class OkHttpUtil {
    private static final long READ_TIMEOUT = 5;
    private static final long WRITE_TIMEOUT = 5;
    private static final long CONN_TIMEOUT = 5;

    @SuppressWarnings("rawtypes")
    public static String addParamToUrl(String url, Map params){
        HttpUrl.Builder httpUrl = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
        Map<String, String> map = new HashMap<String, String>(params);
        for(Map.Entry<String,String> entry:map.entrySet()){
            httpUrl.addQueryParameter(entry.getKey(),entry.getValue());
        }
        return httpUrl.build().toString();
    }

    @SuppressWarnings("rawtypes")
    public static void createWebSocket(final String webUrl, final WebSocketListener wsl, Map params)  {
        if(TextUtils.isEmpty(webUrl)) {
            return;
        }
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(CONN_TIMEOUT, TimeUnit.SECONDS)
                .build();
        String url = addParamToUrl("http://localhost/test", params);
        url = url.replace("http://localhost/test", webUrl);
        Request request = new Request.Builder().url(url).build();
        httpClient.newWebSocket(request, wsl);
        httpClient.dispatcher().executorService().shutdown();
    }

    private OkHttpUtil() {}
}
